package cn.com.zetatech.loader.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.RuntimeMXBean;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhengbs
 */
@Component
@Slf4j
public class ShutdownHookConfig {

    @PostConstruct
    public void init() {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("《===========================================================》");
            log.info("《======================== 项目即将关闭 ========================》");
            log.info("《===========================================================》");
            // 打印JVM版本信息
            log.info("JVM版本: " + System.getProperty("java.version"));
            log.info("JVM供应商: " + System.getProperty("java.vendor"));
            log.info("JVM运行时名称: " + System.getProperty("java.runtime.name"));

            // 获取运行时MXBean来打印JVM参数
            RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
            List<String> inputArguments = runtimeMxBean.getInputArguments();
            log.info("JVM输入参数: " + Arrays.toString(inputArguments.toArray()));

            // 获取内存MXBean来打印内存使用情况
            MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
            MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage();
            MemoryUsage nonHeapMemoryUsage = memoryMxBean.getNonHeapMemoryUsage();

            log.info("堆内存使用情况:");
            log.info("初始: " + heapMemoryUsage.getInit() / 1024 / 1024 + " MB");
            log.info("最大: " + heapMemoryUsage.getMax() / 1024 / 1024 + " MB");
            log.info("已使用: " + heapMemoryUsage.getUsed() / 1024 / 1024 + " MB");
            log.info("提交: " + heapMemoryUsage.getCommitted() / 1024 / 1024 + " MB");

            log.info("非堆内存使用情况:");
            log.info("初始: " + nonHeapMemoryUsage.getInit() / 1024 / 1024 + " MB");
            log.info("最大: " + nonHeapMemoryUsage.getMax() / 1024 / 1024 + " MB");
            log.info("已使用: " + nonHeapMemoryUsage.getUsed() / 1024 / 1024 + " MB");
            log.info("提交: " + nonHeapMemoryUsage.getCommitted() / 1024 / 1024 + " MB");

        }));
    }
}